package com.btcode.db.executer;

import com.btcode.exception.MsgException;

/**
 * 嵌套事务控制
 *
 * @author gislin
 */
public final class MulitTransactionControl {

    private ThreadLocal<TransactionInfo> threadTransactionInfo = new ThreadLocal<TransactionInfo>();

    private volatile static MulitTransactionControl instance;

    private MulitTransactionControl() {

    }

    public static MulitTransactionControl getInstance() {

        if (instance == null) {
            synchronized (MulitTransactionControl.class) {
                if (instance == null) {
                    instance = new MulitTransactionControl();
                }
            }
        }
        return instance;
    }

    public TransactionInfo beginTransaction() {

        TransactionInfo info = threadTransactionInfo.get();

        if (info == null) {
            info = new TransactionInfo();
        }
        else {
            info.addTransactionIndex();
        }

        threadTransactionInfo.set(info);

        return info;
    }

    public void rollback() {
        threadTransactionInfo.remove();
    }

    public TransactionInfo commitTransaction() {
        TransactionInfo info = threadTransactionInfo.get();

        if (info == null) {
            throw new MsgException("无事务可提交");
        }
        else {
            info.cutTransactionIndex();
        }

        if (info.isCommitAble()) {
            threadTransactionInfo.remove();
        }
        else {
            threadTransactionInfo.set(info);
        }

        return info;
    }

    public TransactionInfo getCurrentTransaction(){
        TransactionInfo info = threadTransactionInfo.get();
        return info;
    }

}
